<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div class="">
      <div class="p-2 text-right">
        <a-button type="primary" @click="handleAdd" >新增</a-button>
      </div>
      <Table :dataSource="list" :columns="columns" :pagination="false" :customRow="customRow">
        <template #move>
          &#9769
          <!-- <drag-outlined class="cursor-move" /> -->
        </template>
        <template #tztj="{ record, index }">
          <div class="flex">
            <Select
:options="firstBracketOptions" v-model:value="record['firstBracket']" class="w-80px"
              style="margin-right: 5px" :get-popup-container="getPopupContainer" />

            <Select
:options="formGetFieldsData" v-model:value="record['fieldName']" class="w-200px"
              style="margin-right: 5px" optionFilterProp="label" showSearch
              @change="handleFieldNameChange($event, record)" :get-popup-container="getPopupContainer" />
            <Select
:options="compareOptions5" v-model:value="record['compare']" class="w-100px"
              style="margin-right: 5px" v-if="record['fieldName'] == 'cws_flag' || record['fieldName'] == 'cws_status'"
              :get-popup-container="getPopupContainer" />
            <!-- compareOptions4 -->
            <Select
:options="compareOptions3" v-model:value="record['compare']" class="w-100px"
              style="margin-right: 5px" v-else-if="
                record['fieldType'] == FormField.FIELD_TYPE_TEXT ||
                record['fieldType'] == FormField.FIELD_TYPE_VARCHAR
              " :get-popup-container="getPopupContainer" />
            <Select
:options="compareOptions" v-model:value="record['compare']" class="w-100px"
              style="margin-right: 5px" :get-popup-container="getPopupContainer" v-else />
            <Select
:options="columnNameOptions1" v-model:value="record['columnName']" class="w-100px"
              style="margin-right: 5px" v-if="record['fieldName'] == 'cws_status'"
              :get-popup-container="getPopupContainer" />
            <Select
:options="columnNameOptions2" v-model:value="record['columnName']" class="w-100px"
              style="margin-right: 5px" v-else-if="record['fieldName'] == 'cws_flag'"
              :get-popup-container="getPopupContainer" />
            <!-- <Select
              :options="formGetFieldsMainData"
              v-model:value="record['columnName']"
              class="w-200px"
              style="margin-right: 5px"
              optionFilterProp="label"
              showSearch
              v-if="record['fieldName'] == 'mainFormOpt'"
            /> -->

            <div
class="w-150px" style="margin-right: 5px" v-else-if="
              record['fieldName'] != 'cws_status' &&
              record['fieldName'] != 'cws_flag' &&
              record['fieldName'] != 'mainFormOpt'
            ">
              <Input
v-if="
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_DATE) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_YEAR) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_MONTH) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_ROLE) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT_AND_CHILDREN) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_ADMIN_DEPT) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_PARAM) == 0 ||
                record['columnName'].indexOf(ModuleUtil.FILTER_MAIN_ID) == 0
              " v-model:value="record['columnName']" :readonly="record['columnName'].indexOf(ModuleUtil.FILTER_CUR_DATE) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_YEAR) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_MONTH) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_ROLE) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_CUR_USER_DEPT_AND_CHILDREN) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_ADMIN_DEPT) == 0 ||
                  record['columnName'].indexOf(ModuleUtil.FILTER_MAIN_ID) == 0
                  " />
              <FormCtl
v-else-if="record['fieldName'] && record['formCode']" :formCode="record['formCode']"
                :fieldName="record['fieldName']" v-model:value="record['columnName']"
                style="width: 100px; margin-right: 5px" />
              <Input v-else v-model:value="record['columnName']" />
            </div>

            <div class="w-120px flex items-center">
              <Dropdown :get-popup-container="getPopupContainer">
                <span> {{ record['columnNameTitle'] }}
                  <DownOutlined />
                </span>
                <template #overlay>
                  <Menu @click="({ key }) => handleClickMenu(key, record)">
                    <MenuItem :key="k.value" v-for="k in dropdownMenuOptions">
                    {{ k.label }}
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>
            </div>
            <Select
:options="firstBracketOptions" v-model:value="record['twoBracket']" class="w-80px"
              style="margin-right: 5px" :get-popup-container="getPopupContainer" />
            <Select
:options="logicalOptions" v-model:value="record['logical']" class="w-80px" style="margin-right: 5px"
              v-if="index != list.length - 1" :get-popup-container="getPopupContainer" />
          </div>
        </template>
        <template #action="{ index }">
          <div class="flex">
            <!-- <a-button type="primary" class="mr-2"  @click="handleAdd">新增</a-button> -->
            <a-button type="primary"  @click="handleDelete(index)">删除</a-button>
          </div>
        </template>
      </Table>
    </div>
    <div class="ml-3 mt-3">注: 指定参数的格式为: {$field} 其中field为字段名，如从按钮点击进入模块，则可以带入主表中该字段的值</div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, unref, onMounted } from 'vue';
import { Input, Table, Select, Dropdown, Menu } from 'ant-design-vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { useMessage } from '/@/hooks/web/useMessage';
import { DownOutlined } from '@ant-design/icons-vue';
import {
  firstBracketOptions,
  columns,
  logicalOptions,
  compareOptions2,
  compareOptions3,
  fieldNameOptions,
  compareOptions,
  columnNameOptions1,
  columnNameOptions2,
  dropdownMenuOptions,
  random,
  handleXML,
  setXML,
  compareOptions4,
  compareOptions5,
} from './ConfigurationModal.data';
import { getFormGetFields } from '/@/api/flowManage/flowManage';
import { useRouter } from 'vue-router';
import { isArray } from '/@/utils/is';
import { FormField, WorkflowPredefineDb, ModuleUtil } from '/@/enums/flowManage';
import { FormCtl } from '/@/components/FormCtl';
import { DragOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  name: 'ConfigurationModal',
  components: {
    BasicModal,
    Table,
    Select,
    Input,
    DownOutlined,
    Dropdown,
    Menu,
    MenuItem: Menu.Item,
    FormCtl,
    DragOutlined,
  },
  props: {
    popupContainer: {
      type: String,
      default: ''
    }
  },
  emits: ['success', 'register'],
  setup(props, { emit }) {
    const { createMessage } = useMessage();
    const { currentRoute } = useRouter();
    const list = ref<any>([]);
    const getTitle = '条件';
    const formGetFieldsData = ref<Recordable[]>([]);
    const type = ref('');
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      setModalProps({ confirmLoading: false, width: '80%' });
      try {
        console.log('data', data);
        type.value = data?.type ?? '';
        formGetFieldsData.value = fieldNameOptions;
        if (data?.formGetFieldsData) {
          const newFormGetFieldsData = data.formGetFieldsData.map((item) => {
            return {
              fieldType: item.fieldType,
              formCode: item.formCode,
              value: item.name,
              label: item.title,
            };
          });
          formGetFieldsData.value = [...newFormGetFieldsData, ...fieldNameOptions];
        }
        if (data?.list) {
          list.value = handleXML(data.list);
          list.value.forEach((item) => {
            item.formCode = formGetFieldsData.value.find(
              (el) => el.value == item.fieldName,
            )?.formCode;
          });
          console.log('list.value', list.value);
        } else {
          handleAdd();
        }
      } catch (err) {
        console.log(err);
      }
    });

    async function handleSubmit() {
      try {
        setModalProps({ confirmLoading: true });

        let beginBracketArr: string[] = [];
        let endBracketArr: string[] = [];
        list.value.forEach((item) => {
          for (let v in item) {
            if (item[v] == null || item[v] == 'null') {
              item[v] == '';
            }
          }

          if (item.firstBracket == '(' || item.twoBracket == '(') {
            beginBracketArr.push('(');
          }
          if (item.firstBracket == ')' || item.twoBracket == ')') {
            endBracketArr.push(')');
          }
        });

        console.log('list', list.value);

        if (beginBracketArr.length != endBracketArr.length) {
          createMessage.warning('请检查括弧是否匹配');
          return;
        }
        if (unref(list).length && unref(list).some((item) => !item.compare)) {
          createMessage.warning('请选择比较符号'); // 关系运算符
          return;
        }

        const result = await setXML(unref(list));
        closeModal();
        emit('success', { field: type.value, value: result });
      } catch (err) {
        console.log(err);
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    const handleAdd = () => {
      list.value.push({
        id: random(),
        mainColumn: WorkflowPredefineDb.COMB_COND_TYPE_FIELD,
        columnName: '',
        compare: '',
        firstBracket: '',
        value: '',
        twoBracket: '',
        logical: 'and',
        columnNameTitle: '',
        fieldName:
          isArray(formGetFieldsData.value) && formGetFieldsData.value.length
            ? formGetFieldsData.value[0].value
            : '',
      });
      list.value = [...list.value];
      console.log('list.value', list.value);
    };
    const handleDelete = (index) => {
      list.value.splice(index, 1);
      list.value = [...list.value];
    };

    const handleFieldNameChange = (val, record) => {
      console.log('val, record', val, record, formGetFieldsData.value);
      record['compare'] = '';
      record['columnName'] = '';
      record['columnNameTitle'] = '';
      record['fieldName'] = val;
      record['mainColumn'] = WorkflowPredefineDb.COMB_COND_TYPE_FIELD;
      record['fieldType'] = formGetFieldsData.value.find((item) => item.value == val)?.fieldType;
      record['formCode'] = formGetFieldsData.value.find((item) => item.value == val)?.formCode;
      console.log('handleFieldNameChange', record);
    };

    const formGetFieldsMainData = ref<Recordable[]>([]);
    //获取主表字段
    const getFormGetFieldsMainData = () => {
      try {
        const { query } = currentRoute.value;
        if (query?.formCode) {
          getFormGetFields({ formCode: query.formCode }).then((res) => {
            formGetFieldsMainData.value = res || [];
            if (isArray(formGetFieldsMainData.value)) {
              formGetFieldsMainData.value.forEach((item) => {
                item.value = item.name;
                item.label = item.title;
                delete item.options;
              });
            }
          });
        }
      } catch (err) {
        console.log('getFormGetFieldsMainData', err);
      }
    };
    onMounted(() => {
      getFormGetFieldsMainData();
    });

    //点击菜单
    const handleClickMenu = (key, record) => {
      console.log('key', key);
      record['columnName'] = key;
      if (key === 'mainFormOpt') {
        record['columnName'] = formGetFieldsMainData.value[0]?.value;
      } else {
        record['columnName'] = key;
      }
      const obj2 = dropdownMenuOptions.find((k) => k.value == key);
      if (obj2) {
        record['columnNameTitle'] = obj2?.label;
      }
    };

    const getPopupContainer = (triggerNode) => props.popupContainer? document.querySelector(props.popupContainer):triggerNode?.parentNode;

    let source = 0; // 源目标数据序号
    let target = 0; // 目标数据序号
    // Table行拖拽
    function customRow(record, index) {
      // 只有当具有管理权限时才启用
      // if (!listPage.value.canUserManage) {
      //   return;
      // }
      return {
        props: {
          // draggable: 'true'
        },
        style: {
          // cursor: 'pointer',
        },
        // 鼠标移入
        onMouseenter: (event) => {
          // event.srcElement.tagName始终为TR，无法区分是点在了哪一列
        },
        onMousedown: (event) => {
          if (event.srcElement.tagName === 'TD') {
            let cellIndex = event.srcElement.cellIndex;
            // 如果点击的是第1列（第0列为复选框列），则使可以拖动
            // 因拖拽会影响拷贝粘贴，故限制只能在第1列可拖拽
            if (cellIndex == 0) {
              event.target.draggable = true; // 使可以拖动
            }
          }
        },
        // 开始拖拽
        onDragstart: (event) => {
          // 兼容IE
          let ev = event || window.event;
          // 阻止冒泡
          ev.stopPropagation();
          // 得到源目标数据序号
          source = index;
          console.log(record, index, 'source');
        },
        // 拖动元素经过的元素
        onDragover: (event) => {
          // 兼容 IE
          let ev = event || window.event;
          // 阻止默认行为
          ev.preventDefault();
        },
        // 鼠标松开
        onDrop: (event) => {
          // 兼容IE
          let ev = event || window.event;
          // 阻止冒泡
          ev.stopPropagation();
          // 得到目标数据序号
          target = index;
          const dataFrom = list.value[source];
          list.value.splice(source, 1);
          list.value.splice(target, 0, dataFrom);
          console.log('list', list.value);
          event.target.parentElement.draggable = false; // 取消拖动
          // console.log(record, index, 'target', source, target);
        },
        onDblclick: () => { },
      };
    }

    return {
      registerModal,
      getTitle,
      handleSubmit,
      list,
      columns,
      firstBracketOptions,
      formGetFieldsData,
      logicalOptions,
      compareOptions2,
      handleAdd,
      handleDelete,
      compareOptions,
      compareOptions3,
      compareOptions4,
      columnNameOptions1,
      columnNameOptions2,
      dropdownMenuOptions,
      handleClickMenu,
      handleFieldNameChange,
      formGetFieldsMainData,
      FormField,
      ModuleUtil,
      getPopupContainer,
      customRow,
      compareOptions5
    };
  },
});
</script>
